package me.kuye.jkuye.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import me.kuye.jkuye.core.Controller;

public abstract class Routes {
	private final Map<String, Class<? extends Controller>> map = new HashMap<String, Class<? extends Controller>>();
	private final Map<String, String> viewPathMap = new HashMap<String, String>();
	private static String baseViewPath;

	public abstract void config();

	public Routes add(Routes route) {
		if (route != null) {
			route.config();
			map.putAll(route.map);
			viewPathMap.putAll(route.viewPathMap);
		}
		return this;
	}

	public Routes add(String controllerKey, Class<? extends Controller> contollerClass) {
		return add(controllerKey, contollerClass, controllerKey);
	}

	public Routes add(String controllerKey, Class<? extends Controller> contollerClass, String viewPath) {
		if (controllerKey == null) {
			throw new IllegalArgumentException(" the controllerKey can not be null");
		}
		controllerKey = controllerKey.trim();
		if (controllerKey.equals("")) {
			throw new IllegalArgumentException(" the controllerKey can not be empty");
		}

		if (!controllerKey.startsWith("/")) {
			controllerKey = "/" + controllerKey;
		}
		if (map.containsKey(controllerKey)) {
			throw new IllegalArgumentException("the controllerKey has been exist");
		}
		if (contollerClass == null) {
			throw new IllegalArgumentException("the contollerClass can not be null");
		}
		map.put(controllerKey, contollerClass);

		if (viewPath == null || "".equals(viewPath.trim())) {
			viewPath = controllerKey;
		}
		if (!viewPath.startsWith("/")) {
			viewPath = "/" + viewPath;
		}
		if (!viewPath.endsWith("/")) {
			viewPath = viewPath + "/";
		}
		if (baseViewPath != null) {
			viewPath = baseViewPath + viewPath;
		}
		viewPathMap.put(controllerKey, viewPath);
		return this;
	}

	public Set<Entry<String, Class<? extends Controller>>> getEntrySet() {
		return map.entrySet();
	}

	public String getViewPath(String key) {
		return viewPathMap.get(key);
	}

	public void setBaseViewPath(String baseViewPath) {
		if (baseViewPath == null)
			throw new IllegalArgumentException("The baseViewPath can not be null");
		baseViewPath = baseViewPath.trim();
		if ("".equals(baseViewPath))
			throw new IllegalArgumentException("The baseViewPath can not be empty");

		if (!baseViewPath.startsWith("/"))
			baseViewPath = "/" + baseViewPath;

		if (baseViewPath.endsWith("/"))
			baseViewPath = baseViewPath.substring(0, baseViewPath.length() - 1);

		Routes.baseViewPath = baseViewPath;
	}
}
